package com.it.park.controller.admin;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.it.park.GrapArticle;
import com.it.park.client.service.HomeLogoService;
import com.it.park.client.service.NewsService;
import com.it.park.common.JsonObj;
import com.it.park.common.Page;
import com.it.park.common.SessionUtil;
import com.it.park.constant.Constant;
import com.it.park.model.HomeLogo;
import com.it.park.model.News;
import com.it.park.util.file.FileUtil;

@Controller
@RequestMapping("/admin/news")
public class AdminNewsController {
	private String rootPath=Constant.ADMIN_PATH;

	private Page page = null;
	@Autowired
	private NewsService newsService;
	@Autowired
	private HomeLogoService homeLogoService;
	
	@RequestMapping("listRows")
	@ResponseBody
	public Map<String,Object> listRows(HttpServletRequest request){
			Integer pageNow = Integer.parseInt(request.getParameter("page"));
			Integer rows = Integer.parseInt(request.getParameter("rows"));
			Map<String,Object> map_ = new HashMap<String, Object>();
			Integer total = newsService.selectTotal(map_);
			page = new Page(pageNow,total,rows);
			map_.put("startPos", page.getStartPos());
			map_.put("pageSize", page.getPageSize());
			List<News> list = newsService.selectPagination(map_);
			Map<String,Object> map  =new HashMap<String, Object>();
			map.put("total", total);
			map.put("rows", list);
			return map;
	}
	
	@RequestMapping("newsList")
	public String newsList(HttpServletRequest request){
			return rootPath+"news/newsList";
	}
	
	@RequestMapping("save")
	@ResponseBody
	public JsonObj save(News news,HttpServletRequest request){
		JsonObj json = new JsonObj();
		boolean success = newsService.insertSelective(news);
		if(success){
			json.setMessage("添加成功!");
			json.setSuccess(true);
		}else{
			json.setSuccess(false);
			json.setMessage("添加失败!");
		}
		return json;
	}
	
	@RequestMapping("deleteById")
	@ResponseBody
	public JsonObj deleteById(@RequestParam("id") Integer id,HttpServletRequest request){
		JsonObj json = new JsonObj();
		boolean success = newsService.deleteByPrimaryKey(id);
		if(success){
			json.setMessage("删除成功!");
			json.setSuccess(true);
		}else{
			json.setMessage("删除失败!");
			json.setSuccess(false);
		}
		return json;
	}
	
	@RequestMapping("edit")
	@ResponseBody
	public JsonObj edit(News news,HttpServletRequest request){
		JsonObj json = new JsonObj();
		boolean success = newsService.updateByPrimaryKeySelective(news);
		if(success){
			json.setMessage("修改成功!");
			json.setSuccess(true);
		}else{
			json.setMessage("修改失败!");
			json.setSuccess(false);
		}
		return json;
	}
	
	/**
	 * 一键抓取
	 */
	@RequestMapping("grabNews")
	@ResponseBody
	public JsonObj grabNews(final HttpServletRequest request,final HttpSession session){
		final JsonObj json = new JsonObj();
		new Timer().schedule(new TimerTask() {
			
			@Override
			public void run() {
				System.out.println("开始执行");
				List<String[]> list = GrapArticle.getArticleFrom51CTO("http://zhuanlan.51cto.com/");
				if(list != null && list.size() > 0){
					try {
						for (String[] str : list) {
							News news = new News();
							news.setNewsTitle(str[2]);
							List<News> l = newsService.selectByNewsTitle(news.getNewsTitle());
							if(l != null && l.size() > 0){
								continue;
							}else{
								news.setCreateDate(new Date());
								str[0] = str[0] + "<br><p>注:文章来至于51CTO</p>";
								news.setNewsContents(str[0]);
								news.setClickRate(0);
								news.setCommentNum(0);
								news.setUserId(SessionUtil.getUserID(session));
								newsService.insertSelective(news);
								HomeLogo homeLogo = new HomeLogo();
								homeLogo.setCreateDate(new Date());
								homeLogo.setType(1);
								homeLogo.setIsShow(1);
								homeLogo.setImgName(str[2]);
								BufferedInputStream bis = null;  
								HttpURLConnection httpUrl = null;  
								URL url = null;  
								try {
									url = new URL(str[1]);
									httpUrl = (HttpURLConnection) url.openConnection();  
									httpUrl.connect();  
									bis = new BufferedInputStream(httpUrl.getInputStream());  
								} catch (MalformedURLException e) {
									e.printStackTrace();
								} catch (IOException e) {
									e.printStackTrace();
								}  
								homeLogo.setImgFile(FileUtil.getBytes(bis));
								homeLogo.setNewsId(news.getId());
								homeLogoService.insertSelective(homeLogo);
							}
							
						}
							json.setMessage("抓取成功!");
							json.setSuccess(true);
					} catch (Exception e) {
						json.setMessage("抓取失败!");
						json.setSuccess(false);
						e.printStackTrace();
					}
				}
				
			}
		}, 0, 1000*60*60*12);
		return json;
	}
}
